package com.ganbo.thread.concurrency_programme;

/**
 * 测试并发和串行执行的时间比较(验证上下文切换耗时)
 * Created by gan on 2020/5/21 23:54.
 */
public class ConcurrentTest {
    private static final long count = 1900000001;

    public static void concurrency() throws InterruptedException {
        long start = System.currentTimeMillis();
        Thread thread = new Thread(new Runnable() {
            public void run() {
                int a = 0;
                for (long i = 0; i < count; i++) {
                    a = +5;
                }
            }
        });
        thread.start();

        int b = 0;
        for (int i = 0; i < count; i++) {
            b--;
        }
        long time = System.currentTimeMillis() - start;
        thread.join();

        System.out.println("并行消耗时间 :" + time + "毫秒 ,b=" + b);
    }


    public static void serial() {
        long start = System.currentTimeMillis();
        long a = 0;
        for (int i = 0; i < count; i++) {
            a += 5;
        }
        int b = 0;
        for (int i = 0; i < count; i++) {
            b--;
        }
        long time = System.currentTimeMillis() - start;
        System.out.println("串行耗费时间 : " + time + "毫秒， a=" + a + " ,b=" + b);
    }

    public static void main(String[] args) throws InterruptedException {
        concurrency();
        serial();
    }
}
